package light.head.controller.inv;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import light.head.constant.Msg;
import light.head.constant.Parm;
import light.head.constant.Sys;
import light.head.constant.Url;
import light.head.dao.inv.InvBillConfingDAO;
import light.head.dao.inv.InvDepotDAO;
import light.head.dao.inv.InvOutStorageDAO;
import light.head.dao.inv.InvOutStorageDetailDAO;
import light.head.dao.inv.InvOutStorageItemDAO;
import light.head.dao.inv.InvSaleInfoDAO;
import light.head.dao.inv.InvSaleInfoDetailDAO;
import light.head.dao.inv.InvSaleInfoItemDAO;
import light.head.dao.inv.InvStorageDAO;
import light.head.dao.inv.InvStorageDetailDAO;
import light.head.dao.sys.OrganDAO;
import light.head.dao.sys.UserInfoDAO;
import light.head.enm.RESULT;
import light.head.framework.base.SupporterController;
import light.head.framework.entity.PageBean;
import light.head.framework.utils.ExcelUtils;
import light.head.model.inv.InvDepot;
import light.head.model.inv.InvOutStorage;
import light.head.model.inv.InvOutStorageDetail;
import light.head.model.inv.InvOutStorageItem;
import light.head.model.inv.InvSaleInfo;
import light.head.model.inv.InvSaleInfoDetail;
import light.head.model.inv.InvSaleInfoItem;
import light.head.model.inv.InvStorage;
import light.head.model.inv.InvStorageDetail;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
/**
 * 零售信息
 * @author yy
 *
 */
@Controller
@RequestMapping(value = Url.C_INVSALEINFO)
public class InvSaleInfoController extends SupporterController{
	private InvSaleInfoDAO isiDAO;
	private InvSaleInfoItemDAO isiiDAO;
	private InvSaleInfoDetailDAO isidDAO;
	private InvStorageDAO isDAO;
	private InvStorageDetailDAO detailDAO;
	private InvOutStorageDAO iosDAO;
	private InvOutStorageItemDAO iosiDAO;
	private InvOutStorageDetailDAO iosdDAO;
	private UserInfoDAO userDAO;
	private InvBillConfingDAO ibcfDAO;
	private OrganDAO organDAO;
	private InvDepotDAO idDAO;
	
	private final static String fileName = "零售导出.xls";
	
	@RequestMapping(value = Url.INIT)
	public ModelAndView init(HttpServletRequest request,HttpServletResponse response) throws Exception{
		return new ModelAndView(Url.INVSALEINFO_INIT);
	}
	
	@RequestMapping(value = Url.QUERY)
	public ModelAndView query (HttpServletRequest request, HttpServletResponse response) throws Exception{
		PageBean pb = createPageBean(request);
		Map<String,String> map = createQueryMapByParmName(request, Parm.DELETED,Parm.TIME1,Parm.TIME2,Parm.SNAME,Parm.CASHIER,Parm.DNAME,Parm.DN);
		if (isiDAO.findByMap(organDAO.getSonCodeList(cu_organCode(request)), map, pb) == RESULT.SUCCESS) {
			InvSaleInfo isi =null;
			for (Object o : pb.getResultList()) {
				isi = (InvSaleInfo) o;
				isi.setItemList(isiiDAO.findByIsc(isi.getCode()));
			}
			request.setAttribute(Parm.PAGE_BEAN, pb);
		}
		return new ModelAndView(Url.INVSALEINFO_LIST);
	}
	@RequestMapping(value = Url.DETAIL)
	public ModelAndView detail(HttpServletRequest request, HttpServletResponse response){
		String code = request.getParameter(Parm.CODE);
		if (null != code) {
			InvSaleInfo iis = isiDAO.get(Integer.parseInt(code));
			List<InvSaleInfoItem> itemList = isiiDAO.findByIsc(iis.getCode());
			iis.setItemList(itemList);
			for (InvSaleInfoItem item : itemList) {
				List<InvSaleInfoDetail> detailList = isidDAO.findByIsic(item.getCode());
				item.setDetailList(detailList);
			}
			request.setAttribute(Parm.INVSALEINFO, iis);
		} 
		return new ModelAndView(Url.INVSALEINFO_DETAIL);
	}
	@RequestMapping(value = Url.EDIT)
	public ModelAndView edit(HttpServletRequest request, HttpServletResponse response){
		String code = request.getParameter(Parm.CODE);
		if (null != code) {
			InvSaleInfo is = isiDAO.get(Integer.parseInt(code));
			List<InvSaleInfoItem> itemList = isiiDAO.findByIsc(is.getCode());
			is.setItemList(itemList);
			request.setAttribute(Parm.INVSALEINFO, is);
		} 
		List<InvDepot> typeList = idDAO.findAll(organDAO.getSonCodeList(cu_organCode(request)));
		if (null != typeList && typeList.size() > 0) {
			StringBuffer result = new StringBuffer("[");
			for (InvDepot type : typeList){
				result.append("{");
				result.append("\"dname\":\"" + type.getName() +"\",");
				result.append("\"dc\":\"" + type.getCode() +"\"");
				result.append("},");
			}
			result.deleteCharAt(result.length() - 1).append("]");
			request.setAttribute(Parm.TYPE, result.toString());
		}
		return new ModelAndView(Url.INVSALEINFO_EDIT);
	}
	
	
	
	//零售
	@Transactional
	@RequestMapping(value = Url.SAVE)
	public void save(InvSaleInfo isi, HttpServletRequest request, HttpServletResponse response) throws Exception{
		RESULT result = RESULT.ERROR;
		if (isi == null) return;
		List<InvSaleInfoItem> itemList = isi.getItemList();			// 提交上来的数组
		isi.setDn(ibcfDAO.createBCode(organDAO.getRoot(cu_organCode(request)).getCode(), Sys.B_EIGHT));
		isi.setCt(new Date());
		isi.setDeleted(false);
		isi.setCu(cu_code(request));
		isi.setOc(cu_organCode(request));
		result = isiDAO.add(isi); 	// 零售记录
		//保存出库信息
		InvOutStorage ios = new InvOutStorage();
		ios.setDn(ibcfDAO.createBCode(organDAO.getRoot(cu_organCode(request)).getCode(), Sys.B_FOUR));
		ios.setCt(new Date());
		ios.setCu(cu_code(request));
		ios.setDeleted(false);
		ios.setOc(cu_organCode(request));
		ios.setType(Sys.B_TWO);
		result = iosDAO.add(ios);
		// 保存
		for (InvSaleInfoItem item : itemList) {
			if (item != null && item.getCc() != null && item.getCount() != null){
				// 保存零售库明细
				item.setIsc(isi.getCode());
				item.setDeleted(false);
				result = isiiDAO.add(item);
				//保存出库明细
				InvOutStorageItem iosi = new InvOutStorageItem();
				iosi.setCc(item.getCc());
				
				iosi.setDeleted(false);
				iosi.setIosc(ios.getCode());
				iosi.setNumber(item.getCount());
				result = iosiDAO.add(iosi);
				// 保存库存
				Integer oc = organDAO.getRoot(cu_organCode(request)).getCode();
				List<InvStorage> dbList = isDAO.findByCcDc(item.getCc(),isi.getDc(), organDAO.getSonCodeList(cu_organCode(request)));
				String serial = detailDAO.findByCcOc(item.getCc(), organDAO.getSonCodeList(oc));
				if (null != dbList && dbList.size() > 0) {
					if (dbList.get(0).getCount().intValue() <= 0 ) {
						print(response, Msg.EXISTS);
						return;
					}if (dbList.get(0).getCount().intValue() < item.getCount().intValue()) {
						print(response, Msg.NOT_FIND);
						return;
					}
					dbList.get(0).setCount(dbList.get(0).getCount() - item.getCount());
					dbList.get(0).setRemark(item.getRemark());
					result = isDAO.upd(dbList.get(0));
					if (item.getSnc().intValue() == 3) {
						//保存零售串号
						for(InvSaleInfoDetail isid : item.getDetailList()){
							if (isid != null && isid.getSerial() != null){
								isid.setDeleted(false);
								isid.setIsic(item.getCode());
								result = isidDAO.add(isid);	
								// 删除库存串号
								if (result == RESULT.SUCCESS){
									List<InvStorageDetail> isdList = detailDAO.findByOc(isid.getSerial(), organDAO.getSonCodeList(oc));
									if (null != isdList && isdList.size() > 0){
										result = detailDAO.del(isdList.get(0));	
									}	
								}
								//保存出库串号
								InvOutStorageDetail iosd = new InvOutStorageDetail();
								iosd.setDeleted(false);
								iosd.setIosic(iosi.getCode());
								iosd.setSerial(isid.getSerial());
								result = iosdDAO.add(iosd);
							}
						}
					}else if (item.getSnc().intValue() == 2 && serial != null){
						// 保存出库详情
						InvOutStorageDetail iosd = new InvOutStorageDetail();
						iosd.setIosic(iosi.getCode());
						iosd.setDeleted(false);
						iosd.setSerial(serial);
						result = iosdDAO.add(iosd);
						// 保存零售详情
						InvSaleInfoDetail isid = new InvSaleInfoDetail();
						isid.setDeleted(false);
						isid.setIsic(item.getCode());
						isid.setSerial(serial);
						result = isidDAO.add(isid);
					}
				} 
			}else {
				print(response, Msg.ERROR);
				return;
			}
		}
		print(response, Msg.SUCCESS);
	}
	
	
	/**
	 * 查询库存商品
	 */
	@RequestMapping(Url.S_INIT)
	public ModelAndView sInit(HttpServletRequest request, HttpServletResponse response) throws Exception {
		request.setAttribute(Parm.INDEX, request.getParameter(Parm.INDEX));
		request.setAttribute(Parm.DC, request.getParameter(Parm.DC));
		System.out.println(request.getParameter(Parm.DC));
		System.out.println(request.getParameter(Parm.INDEX));
		return new ModelAndView(Url.INVSALEINFO_S_INIT);
	}
	
	@RequestMapping(Url.S_LIST)
	public ModelAndView sList(HttpServletRequest request, HttpServletResponse response) throws Exception {
		PageBean pageBean = createPageBean(request);
		Map<String, String> map = createQueryMapByParmName(request, Parm.OC, Parm.NAME,Parm.FAST);
		String  a = request.getParameter(Parm.DC);
		if (RESULT.SUCCESS == isDAO.findByMap_2(Integer.parseInt(a),organDAO.getSonCodeList(cu_organCode(request)), map,pageBean)) {
			request.setAttribute(Parm.PAGE_BEAN, pageBean);
		}
		return new ModelAndView(Url.INVSALEINFO_S_LIST);
	}
	
	/**
	 * 查询用户
	 */
	@RequestMapping(Url.AIDUSER_INIT)
	public ModelAndView aidUserInit(HttpServletRequest request, HttpServletResponse response) throws Exception {
		request.setAttribute(Parm.PIB, request.getParameter(Parm.PIB));
		System.out.println(request.getParameter(Parm.PIB));
		return new ModelAndView(Url.INVSALEINFO_USER_INIT);
	}

	@RequestMapping(Url.AIDUSER_LIST)
	public ModelAndView aidUserList(HttpServletRequest request, HttpServletResponse response) throws Exception {
		PageBean pageBean = createPageBean(request);
		Map<String, String> map = createQueryMapByParmName(request, Parm.REAL_NAME,Parm.DELETED);
		Integer oc = organDAO.getRoot(cu_organCode(request)).getCode();
		userDAO.findByMapAndOc(organDAO.getSonCodeList(oc),map,pageBean);
			request.setAttribute(Parm.PAGE_BEAN, pageBean);
		return new ModelAndView(Url.INVSALEINFO_USER_LIST);
	}
	//判断序列号是否是该库存下的商品所属
	@RequestMapping(value = Url.VERIFY2)
	public void serial2(HttpServletRequest request, HttpServletResponse response)throws Exception {
		String serial = request.getParameter("serial");
		String cc = request.getParameter("cc");
		String dc = request.getParameter("dc");
		List<InvStorageDetail> detailList = detailDAO.findBySerialCcDc(serial,Integer.parseInt(cc),Integer.parseInt(dc));
		if (detailList != null && detailList.size() > 0) {
			print(response, Msg.SUCCESS);
			
		} else {
			print(response, Msg.ERROR);
			return;
		}
	}
	
	// 用序列号到库存查询出对应的商品信息
		@RequestMapping(value = Url.VERIFY)
		public void loadCommodity(HttpServletRequest request, HttpServletResponse response)throws Exception {
			String serial = request.getParameter(Parm.SERIAL);
			String a = request.getParameter(Parm.DC);
			Object obj = detailDAO.findBySerialDc(serial,Integer.parseInt(a), organDAO.getSonCodeList(cu_organCode(request)));
			
			if (null != obj) {
				Object[] comm = (Object[]) obj;
				Byte snc = null != comm[2] ? (Byte) comm[2] : null;
				String name = "";
				if (null !=  snc && snc.byteValue() == 1)
					name = "不需要序列号";
				else if (null !=  snc && snc.byteValue() == 2)
					name = "同类序列号: ";
				else
					name = "唯一序列号";
						
				StringBuffer result = new StringBuffer("{");
				
				result.append("\"cc\":\"" + comm[0] +"\",");
				result.append("\"cname\":\"" + comm[1] +"\",");
				result.append("\"snc\":\"" + comm[2] +"\",");
				result.append("\"s\":\"" + name +"\",");
				result.append("\"price\":\"" + comm[3] +"\",");
				result.append("\"serial\":\"" + comm[4] +"\",");
				result.append("\"count\":\"" + comm[7] +"\"");
				result.append("}");
				print(response, result.toString());
			} else {
				return;
			}
		}
	
	
	// 库存导出
	@RequestMapping(Url.EXCEL_EXPORT)
	public void exclExport(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String, String> map = createQueryMapByParmName(request, Parm.DELETED,Parm.DNAME,Parm.CNAME,Parm.ON,Parm.TIME1,Parm.TIME2);
		map.put(Parm.CU, cu_code(request).toString());
		map.put(Parm.OC, cu_organCode(request).toString());
		List<InvSaleInfoItem> list = isiDAO.findByMap1(organDAO.getSonCodeList(cu_organCode(request)), map);
		response.setContentType("application/vnd.ms-excel");
		response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("UTF-8"), "ISO-8859-1"));
		ExcelUtils.writeExcel(list, "零售信息", response.getOutputStream(), null, null);
	}
		
	
	
	
	@Autowired
	public void setIsiDAO(InvSaleInfoDAO isiDAO) {
		this.isiDAO = isiDAO;
	}
	@Autowired
	public void setIsiiDAO(InvSaleInfoItemDAO isiiDAO) {
		this.isiiDAO = isiiDAO;
	}
	@Autowired
	public void setIsidDAO(InvSaleInfoDetailDAO isidDAO) {
		this.isidDAO = isidDAO;
	}
	@Autowired
	public void setIsDAO(InvStorageDAO isDAO) {
		this.isDAO = isDAO;
	}
	@Autowired
	public void setDetailDAO(InvStorageDetailDAO detailDAO) {
		this.detailDAO = detailDAO;
	}
	@Autowired
	public void setIbcfDAO(InvBillConfingDAO ibcfDAO) {
		this.ibcfDAO = ibcfDAO;
	}
	@Autowired
	public void setOrganDAO(OrganDAO organDAO) {
		this.organDAO = organDAO;
	}
	@Autowired
	public void setUserDAO(UserInfoDAO userDAO) {
		this.userDAO = userDAO;
	}
	@Autowired
	public void setIosDAO(InvOutStorageDAO iosDAO) {
		this.iosDAO = iosDAO;
	}
	@Autowired
	public void setIosiDAO(InvOutStorageItemDAO iosiDAO) {
		this.iosiDAO = iosiDAO;
	}
	@Autowired
	public void setIosdDAO(InvOutStorageDetailDAO iosdDAO) {
		this.iosdDAO = iosdDAO;
	}
	@Autowired
	public void setIdDAO(InvDepotDAO idDAO) {
		this.idDAO = idDAO;
	}
}
